﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Timers;
using WeiBeeCommon.Helpers;

/// <summary>
/// Summary description for TimedJob
/// </summary>
public class TimedJob
{
    private static Timer _timer = new Timer();
	private TimedJob()
	{
        _timer.Interval = 5000.0d;
        _timer.Enabled = true;
        _timer.Elapsed += TimerElapsed;
        _timer.Start();
	}

    private readonly List<WeiBeeAdd> _weibeeJobs = new List<WeiBeeAdd>();
    public string Logfile = @"D:\WebPages\Cachecallback.txt";
    void TimerElapsed(object sender, ElapsedEventArgs e)
    {
        try
        {
            using (var writer = new System.IO.StreamWriter(Logfile, true))
            {
                writer.WriteLine("{0} : {1} jobs in cache", DateTime.Now, _weibeeJobs.Count);
                if (_weibeeJobs.Count > 1)
                {
                    writer.WriteLine(" Job 0 - {0}", _weibeeJobs[0].ScheduledTime.ToString());
                }

                var adds = _weibeeJobs.Where(w => DateTime.Compare(w.ScheduledTime, DateTime.UtcNow) <= 0);
                foreach (var w in adds)
                {
                    w.Add();
                    writer.WriteLine("Add Twitter: {0}", DateTime.Now);
                    _weibeeJobs.Remove(w);
                }
                writer.Close();
            }
        }
        catch 
        {
            //Debug.WriteLine(x);
        }
    }
    private static TimedJob _timedJob = new TimedJob();
    static public TimedJob GetInstance()
    {
        return _timedJob;
    }

    /// <summary>
    /// Add one schedule WeiBee Add twitter job in the list
    /// </summary>
    /// <param name="wbAdd">WeiBee Add Twitter</param>
    public void Add(WeiBeeAdd wbAdd)
    {
        _weibeeJobs.Add(wbAdd);
    }
}